import pytest
from selenium import webdriver
import time
import os
from common.file_handler import FileHandler


"""
scope = session 所有用例执行之前和之后
scope = package 所有的包执行之前和之后
scope = module 所有的模块执行之前和之后
scope = class 所有的类执行之前和之后
scope = function 每个测试用例之前和之后
"""

Chrome_path = FileHandler.parse_yaml('./test_data/chrome_path.yaml')


@pytest.fixture(scope='function', autouse=True)
def driver():
    options = webdriver.ChromeOptions()
    options.binary_location = Chrome_path.get('binary_location')
    driver = webdriver.Chrome(executable_path=Chrome_path.get('executable_path'))
    driver.maximize_window()
    driver.implicitly_wait(5)

    yield driver    # yield之前代表所有用例执行之前的操作，后面代表所有用例执行之后的操作
    time.sleep(4)
    driver.quit()


@pytest.fixture(scope='function', autouse=True)
def screenshot(driver):
    """
    每个测试用例执行之前，之后的操作
    :return:
    """

    yield  # 每个用例执行之后进行截屏操作
    time.sleep(2)
    screenshot_pngs = os.path.join(os.path.dirname(__file__), 'screenshots')
    if not os.path.exists(screenshot_pngs):
        os.mkdir(screenshot_pngs)
    filename = time.strftime("%y_%m_%d_%H_%M_%S")
    png_file = os.path.join(screenshot_pngs, filename+'.png')
    driver.save_screenshot(png_file)
